package deng.boob.service.impl;

import deng.boob.entity.User;
import deng.boob.service.UserService;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    Dao dao;

    @Override
    public boolean insert(User user) {
        encryptPassword(user);
        if (exist(user.getUsername()))
            return false;
        user.setRoles("ROLE_USER");
        dao.insert(user);
        return true;
    }

    @Override
    public User getByUsername(String username) {
        return dao.fetch(User.class, Cnd.where("username", "=", username));
    }


    private boolean exist(String username){
        User byUsername = getByUsername(username);
        return (byUsername != null);
    }

    /**
     * 加密密码
     */
    private void encryptPassword(User user){
        String password = user.getPassword();
        password = new BCryptPasswordEncoder().encode(password);
        user.setPassword(password);
    }
}
